<template>
  <view>
    <uni-forms-item :required="isRequired" :label="customLabel || labelTxt" :name="uploadKey">
      <view @click="uploadFile">
        <slot>
          <view class="flex justify-between items-center py-8">
            <view v-if="!uploadList.length" class="text-[#cacaca] text-xs">{{ uploadPlaceholder }}</view>
            <view v-else class="text-xs">已选择{{ uploadList.length }}个文件</view>
            <view class="flex items-center">
              <uni-icons
                :type="['image', 'payment', 'imgFile'].includes(props.fileType) ? 'image' : 'paperclip'"
                color="#ccc"
                size="24"
              />
              <uni-icons type="right" color="#ccc" size="14" />
            </view>
          </view>
        </slot>
      </view>
    </uni-forms-item>
    <view v-if="uploadList.length">
      <template v-if="['image', 'payment', 'imgFile'].includes(props.fileType)">
        <view class="flex flex-wrap">
          <view class="relative mr-12 mb-12" v-for="(item, index) in uploadList" :key="index">
            <image :src="item.fileUrl" class="w-48 h-48 rounded-[6px]" mode="aspectFill" @click="previewImage(index)" />
            <view
              class="flex justify-center items-center absolute top-[-4px] right-[-4px] w-24 h-24 bg-gray-700 rounded-full"
            >
              <uni-icons type="closeempty" size="16" color="#fff" @click="deleteFile(index)" />
            </view>
          </view>
        </view>
      </template>
      <template v-else>
        <view
          class="flex justify-between items-center py-8 border-b border-solid border-[#F0F0F0] last:border-b-0"
          v-for="(item, index) in uploadList"
          :key="index"
        >
          <view class="flex-1 mr-20 text-font_gray line-clamp-1">{{ item.fileName }}</view>
          <view>
            <uni-icons type="closeempty" size="24" color="#e43d33" @click="deleteFile(index)" />
          </view>
        </view>
      </template>
    </view>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue';
import { hostUrl } from '@/libs/config.js';
import { USER_ACCESS_TOKEN } from '@/libs/config.js';
import { useUserIdentity } from '@/utils/usePublic';
import { showToast, showLoginConfirm } from '@/utils/utils';
import UploadClass from '@/utils/upload.js';

const userIdentity = useUserIdentity();
const emits = defineEmits(['change']);
const props = defineProps({
  fileList: {
    type: Array,
    default: () => [],
  },
  limit: {
    type: Number,
    default: 5,
  },
  fileType: {
    type: String,
    default: 'all', // all | image | video
  },
  isNeedFileId: {
    type: Boolean,
    default: true,
  },
  uploadConfig: {
    type: Object,
    default: () => {},
  },
  isUploadToQny: {
    type: Boolean,
    default: false,
  },
  uploadKey: {
    type: String,
    default: '',
  },
  isRequired: {
    type: Boolean,
    default: false,
  },
  uploadPlaceholder: {
    type: String,
    default: '请选择附件',
  },
  customLabel: {
    type: String,
    default: '',
  },
});
const labelTxt = {
  all: '附件',
  image: '图片',
  video: '视频',
  resume: '个人简历',
  payment: '凭证',
  imgFile: '附件',
}[props.fileType];

// 上传文件
const uploadList = ref(props.fileList);
watch(
  () => props.fileList,
  newVal => {
    uploadList.value = newVal;
  },
  { deep: true },
);
function uploadFile() {
  if (!userIdentity.isLogin) {
    showLoginConfirm();
    return;
  }
  if (!userIdentity.isCustomer) {
    showToast('您还不是我们的客户哦~');
    return;
  }
  if (uploadList.value.length >= props.limit) {
    showToast(`最多上传${props.limit}个文件`);
    return;
  }
  if (props.isUploadToQny) {
    const uploadInstance = new UploadClass({
      limit: props.limit,
      uploadType: ['image', 'payment', 'imgFile'].includes(props.fileType) ? 'image' : 'all',
      isNeedFileId: props.isNeedFileId,
    });
    uploadInstance.uploadFile(props.uploadConfig).then(res => {
      uploadList.value.push(...res);
      emits('change', uploadList.value);
    });
  } else {
    uploadToServer().then(res => {
      uploadList.value.push(...res);
      emits('change', uploadList.value);
    });
  }
}
// 删除上传文件
function deleteFile(index) {
  uploadList.value.splice(index, 1);
  emits('change', uploadList.value);
}
// 预览图片
function previewImage(index) {
  uni.previewImage({
    current: index,
    urls: uploadList.value.map(item => item.fileUrl),
  });
}

function uploadToServer() {
  return new Promise(resolve => {
    if (props.fileType === 'file') {
      // #ifdef MP-WEIXIN
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        success(res) {
          wx.showLoading({
            title: '上传中',
          });
          chooseFileComplete(res.tempFiles, resolve);
        },
      });
      // #endif
      //  #ifndef MP-WEIXIN
      uni.chooseFile({
        type: 'all',
        extension: ['.doc', '.docx', '.pdf'],
        success(res) {
          wx.showLoading({
            title: '上传中',
          });
          chooseFileComplete(res.tempFiles, resolve);
        },
      });
      // #endif
    } else {
      uni.chooseImage({
        count: props.limit - uploadList.value.length,
        sourceType: ['album', 'camera'],
        success: res => {
          uni.showLoading({
            title: '上传中',
          });
          chooseFileComplete(res.tempFiles, resolve);
        },
      });
    }
  });
}

function chooseFileComplete(tempFiles, resolve) {
  toBackEnd(tempFiles).then(list => {
    resolve(list);
    // emits('change', uploadList.value);
  });
}

function toBackEnd(files) {
  const token = uni.getStorageSync(USER_ACCESS_TOKEN);
  return new Promise(resolve => {
    const result = [];
    let count = 0;
    for (let i = 0; i < files.length; i++) {
      uni.uploadFile({
        url: `${hostUrl}/channel/upload_file`,
        filePath: files[i].path,
        header: {
          Authorization: `Bearer ${token}`,
        },
        name: 'file',
        formData: {
          source: props.uploadKey,
        },
        success: res => {
          const rt = JSON.parse(res.data);
          if (rt.code === 200) {
            const { data } = rt;
            result.push({
              fileName: data.file_name,
              fileUrl: data.file_url,
              fileId: data.id,
            });
          } else {
            showToast(rt.message);
          }
        },
        complete: () => {
          count++;
          if (count === files.length) {
            uni.hideLoading();
            resolve(result);
          }
        },
      });
    }
  });
}

defineExpose({
  uploadList,
});
</script>
